package com.lm.liaoming.tool;

/**
 * Created by Administrator on 2017/3/3.
 */

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.lm.liaoming.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import androidx.core.content.FileProvider;


/**
 * 版本更新工具类
 * 韦敏敏
 */
public class UpdateManager {

    private final String savePath = StorageHelper.getSDCardPath();
    private final int DOWN_UPDATE = 1;
    private final int DOWN_OVER = 2;
    private final String downloadurl;
    private Thread downLoadThread;

    private boolean interceptFlag = false;
    private Context mContext;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    break;
                case DOWN_OVER:
                    installApk((Context) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };
    private File ApkFile;

    /**
     * 自动安装APK
     *
     * @param context
     */
    public UpdateManager(Context context, String downloadurl) {
        this.mContext = context;
        this.downloadurl = downloadurl;
    }

    //外部接口让主Activity调用
    public void checkUpdateInfo() {
        showNoticeDialog();
    }

    private void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        alertDialog.getWindow().setContentView(R.layout.updata);
        //关闭按钮
        Button closeBtn = alertDialog.getWindow().findViewById(R.id.btn_cancel);
        //版本更新内容
        TextView upgradeText = alertDialog.getWindow().findViewById(R.id.tv_upgrade_text);
        Button upgradeBtn = alertDialog.getWindow().findViewById(R.id.btn_update);
        //立即更新
        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.cancel();
                alertDialog.dismiss();
            }
        });
        upgradeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
//                downloadApk();
            }
        });
        //不更新
        alertDialog.setCancelable(true);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    public interface OnUpdateManager {
        void loading(int totalSize, int currentSize);
    }

    public void downloadApk(final Context context, final OnUpdateManager onUpdateManager) {
        downLoadThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(downloadurl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    String apkFile = System.currentTimeMillis()+".apk";
                    ApkFile = new File(savePath + File.separator + apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);
                    int totalSize = conn.getContentLength();
                    int count = 0;
                    byte[] buf = new byte[1024];
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        //更新进度
                        onUpdateManager.loading(totalSize, count);
                        if (numread <= 0) {
                            //下载完成通知安装
                            Message msg = new Message();
                            msg.obj = context;
                            msg.what = DOWN_OVER;
                            mHandler.sendMessage(msg);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!interceptFlag);//点击取消就停止下载.
                    fos.close();
                    is.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        /**
         * 下载apk
         */

        downLoadThread.start();
    }

    /**
     * 安装apk
     */
    public void installApk(Context context) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        Uri photoURI;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0及以上
            photoURI = FileProvider.getUriForFile(context, "com.dai.app.FileProvider", ApkFile);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            photoURI = Uri.fromFile(ApkFile);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        i.setDataAndType(photoURI, "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }


}



